const util = require('../util');

class RouterTemplate {
  constructor(tables) {
    this.tables = tables;
  }

  generateFile() {
    this.text = '';
    this.header();
    this.start();
    this.end();
    return this.text;
  }

  header() {
    this.text += `const config = require('../configs'),
    Router = require('koa-router'),
    router = new Router({
      prefix: config.app.routerBaseApi
    });\n\n`;
  }

  start() {
    let str1 = '';
    let str2 = '';
    for (let i = 0; i < this.tables.length; i++) {
      let tableName = util.underlineToHump(this.tables[i]);
      let upTableName = util.upFirst(tableName);
      let tableRoute = this.tables[i].replace(/_/g,'/');
      str1 += `var ${tableName} = require('../controllers/${this.tables[i]}');`;
      str2 += `.post('/v1/${tableRoute}',${tableName}.create${upTableName})\n`;
      str2 += `.get('/v1/${tableRoute}s',${tableName}.get${upTableName}s)\n`;
      str2 += `.get('/v1/${tableRoute}',${tableName}.get${upTableName})\n`;
      str2 += `.put('/v1/${tableRoute}',${tableName}.update${upTableName})\n`;
    }
    this.text += str1;
    this.text += `\n`;
    this.text += `router\n`;
    this.text += str2;
    this.text += ';\n\n';
  }
  end() {
    this.text += `exports = module.exports = router;`;
  }
}

exports = module.exports = RouterTemplate;
